package com.borya.service.server.impl;

import com.alibaba.fastjson.JSONObject;
import com.borya.constant.RedisConstant;
import com.borya.dao.AppConfDAO;
import com.borya.dao.MerchantDAO;
import com.borya.dao.MessageDAO;
import com.borya.dao.UserDAO;
import com.borya.framework.annotation.Autowired;
import com.borya.framework.annotation.Component;
import com.borya.framework.util.ObjectUtils;
import com.borya.model.db.*;
import com.borya.model.entity.GavePromotion;
import com.borya.model.entity.MerchantProInfo;
import com.borya.model.entity.SelfRegistering;
import com.borya.model.entity.SmsInfo;
import com.borya.model.enumcation.OtherConfType;
import com.borya.service.impl.BaseServiceImpl;
import com.borya.service.server.UserService;
import com.borya.statuscode.StatusCode;
import com.borya.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.time.Clock;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Component("server_userServiceImpl")
public class UserServiceImpl extends BaseServiceImpl implements UserService {

	private Logger log = Logger.getLogger(getClass());
	private static final String KAMENG_SMSCODE = "ka_meng:smscode";
	@Autowired("userDAOImpl")
	private UserDAO userDAO;
	@Autowired("merchantDAO")
	private MerchantDAO merchantDAO;
	@Autowired("messageDAO")
	private MessageDAO messageDAO;

	@Autowired("appConfDAOImpl")
	private AppConfDAO appConfDAO;

	public UserDAO getUserDAO() {
		return userDAO;
	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	public MerchantDAO getMerchantDAO() {
		return merchantDAO;
	}

	public void setMerchantDAO(MerchantDAO merchantDAO) {
		this.merchantDAO = merchantDAO;
	}

	@Override
	public String getSmsCode(JSONObject json) {
		final String userId = json.getString("userId");
		String receiver = json.getString("receiver");
		String authCode = json.getString("authCode");
		String msgContent = json.getString("msgContent");
		long timeout = json.getLongValue("timeout");

		if (StringUtils.isBlank(receiver) || StringUtils.isBlank(msgContent) || StringUtils.isBlank(userId)
				|| timeout <= 0) {
			log.warn("参数错误," + json);
			return StatusCode.PARAM_ERROR.toJSON();
		}
		SmsInfo smsInfo = new SmsInfo();
		smsInfo.setUserId(userId);
		smsInfo.setAuthCode(authCode);
		smsInfo.setRequesttype("3");
		smsInfo.setTimeoutTime(timeout);
		smsInfo.setUseNum(1);

		String result = process_sms(userId, receiver, msgContent, smsInfo);
		if (result == null) {
			return StatusCode.SUCCESS.toJSON();
		} else {
			return result;
		}
	}

	/**
	 * 向用户手机发送一条短信
	 * 
	 * @param phone
	 * @return
	 */
	private String process_sms(String userId, String phone, String msgContent, SmsInfo smsInfo) {
		boolean bool = getUserDAO().redis_hset(KAMENG_SMSCODE, userId, smsInfo.getBeanJson());
		log.debug("redis save result:" + (bool ? "success" : "failed") + " SMS CODE:" + smsInfo.getBeanJson());
		boolean ok = sendMsg(phone, msgContent);
		if (ok) {
			log.info("[SMS] 向用户:" + phone + "发送短信验证码成功");
			return null;
		} else {
			getUserDAO().redis_del(KAMENG_SMSCODE, userId);
			log.info("[SMS] 向用户：" + phone + "发送短信:[" + msgContent + "],法发送失败！");
			return StatusCode.SYSTEM_EXCEPTION.toJSON("获取短信验证码失败，请稍后再试");
		}

	}

	@Override
	public String registAudited(JSONObject json) {
		log.debug("registAudited:" + json);
		final String orderId = json.getString("orderId");
		final String dealer_id = json.getString("dealerId");
		final String devMac = json.getString("devMac");
		final int result = json.getIntValue("result");
		final String beforeStatus = json.getString("beforeStatus");
		final String remarks = json.getString("remarks");
		if (ObjectUtils.isNullOrEmpty(orderId) || ObjectUtils.isNullOrEmpty(dealer_id) || ObjectUtils.isNull(devMac)
				|| ObjectUtils.isNull(beforeStatus) || !(result == 1 || result == 2 || result == 4)
				|| ObjectUtils.isNull(remarks)) {
			log.warn("param error, " + json.toString());
			return StatusCode.PARAM_ERROR.toJSON();
		}
		Merchant m = userDAO.getMerchantStatus(dealer_id);
		if (Objects.isNull(m) || 3 != m.getStatus()) {
			log.warn("merchant status error," + m);
			return StatusCode.CONDITION_DEL_ING.toJSON("重复请求");
		}
		final int detailType = m.getDetailType();
		AsyncUtils.executor().execute(() -> {
			try {
				SelfRegistering s = getUserDAO().getRegistInfo(orderId);
				if (ObjectUtils.isNull(s)) {
					log.warn("not found orderInfo," + orderId);
					return;
				}
				if (1 == result || 4 == result) {
					auditSuccess(orderId, s, detailType);
					return;
				}
				sendMsg(s.getUser_id(), remarks, result, s.getIsManage());
				boolean r = getUserDAO().updateWhenAuditFail(dealer_id, devMac, Integer.parseInt(beforeStatus));
				log.debug("update result " + (r ? "成功" : "失败") + "," + json);
			} catch (Exception e) {
				log.error(e.getMessage(), e);
			}
		});

		return StatusCode.SUCCESS.toJSON();
	}

	private void auditSuccess(final String orderId, SelfRegistering s, int detailType) {
		final String scopeId = s.getScopeId();
		Scope scope = getMerchantDAO().findScopeById(scopeId);
		if (ObjectUtils.isNull(scope)) {
			log.warn("not found Scope," + scopeId);
			return;
		}
		String newPhoneModel = getModelStr(s.getPhoneModel(), scope.getPhoneModel());
		String newPackModel = getModelStr(s.getPackModel(), scope.getPackModel());
		s.setPhoneModel(newPhoneModel);
		s.setPackModel(newPackModel);

		s.setType(scope.getType());// 待开通区域售卡权限
		String result = geDealerId(s.getCompany_name(), s.getUser_name(), s.getPhone());
		if (ObjectUtils.isNullOrEmpty(result)) {
			log.warn("获取dealerId失败." + orderId);
			sendMsg(s.getUser_id(), "获取dealerId失败，请重新激活。", 2, s.getIsManage());
			boolean r = getUserDAO().updateWhenAuditFail(s.getOldDealerId(), s.getKMRecordCode(), 1);
			log.info(orderId + "获取dealerId失败，商户、设备还原" + r);
			return;
		}
		JSONObject rJso = JSONObject.parseObject(result);
		if (ObjectUtils.nonEqual("200", rJso.getString("code"))) {
			log.warn("获取dealerId失败," + orderId);
			sendMsg(s.getUser_id(), rJso.getString("msg") + "。获取dealerId失败，请重新激活。", 2, s.getIsManage());
			boolean r = getUserDAO().updateWhenAuditFail(s.getOldDealerId(), s.getKMRecordCode(), 1);
			log.info(orderId + "获取dealerId失败，商户、设备还原" + r);
			return;
		}
		String dealerId = rJso.getJSONObject("data").getString("dealerId");

		String invite;
		if (s.getSourceType() == Constant.SourceType.KAMENG) {
			// 喜牛的已有邀请码 不需要重新生成
			invite = userDAO.getInviteCode();
			if (invite == null) {
				log.error("db error");
				sendMsg(s.getUser_id(), "系统异常", 2, s.getIsManage());
				return;
			}
			s.setInvite_code(invite);
		}

		final long curTime = Clock.systemDefaultZone().millis();
		s.setDealer_id(dealerId);
		s.setModifyTime(curTime);
		s.setStatus(0);// 已激活
		Map<String, String> baseMap = null;
		if (s.getSourceType() == Constant.SourceType.XINIU) {
			baseMap = appConfDAO.getConfValuesResMap(OtherConfType.BASE_SUCCESS_NUM, s.getDetailType());
		}

		ModelInfo modelInfo = getUserDAO().getDealerModel(s.getPopchannel());
		if (modelInfo != null) {
			s.setCheckLocationFlag(modelInfo.getCheckLocationFlag());
			s.setCheckLocation(modelInfo.getCheckLocation());
		}
		boolean r = userDAO.activeMerchant(s, orderId, baseMap, detailType);
		if (!r) {
			log.warn("activeMerchant return " + r);
			sendMsg(s.getUser_id(), "系统异常", 2, s.getIsManage());
			return;
		}
		// 添加特殊商户信息 如新零售
		addSpecialDealerModel(s.getPopchannel(), s.getDealer_id(), s.getCompany_name());
		//限制权限的控制
		addLimitPower(s, modelInfo);
		sendMsg(s.getUser_id(), "绑定成功", 1, s.getIsManage());
		if (ObjectUtils.isNullOrEmpty(s.getSuper_dealer_id()) && ObjectUtils.nonNullOrEmpty(s.getPopchannel())) {
			boolean r3 = getUserDAO().noSuperSetInfo(s);
			log.debug("getUserDAOImpl noSuperSetInfo return " + r3);
			if (r3) {
				AsyncUtils.executor().execute(() -> {
					String url1 = "http://60.205.208.150:8898/NoticeHub/?fun=onconnected";
					String h1 = HTTPUtils.sendGet(url1);
					log.debug(url1 + " return " + h1);
					String url2 = "http://60.205.208.150:8898/NoticeHub/?tdealeid=" + s.getSuper_dealer_id()
							+ "&sdealeid=" + s.getDealer_id() + "&recordcode=" + s.getKMRecordCode() + "&datatime="
							+ DateUtils.format(System.currentTimeMillis(), "yyyy-MM-dd%20HH:mm");
					String h2 = HTTPUtils.sendGet(url2);
					log.debug(url2 + " return " + h2);
				});
			}
		}

		/** 2018-06-05 推广佣金 **/
		addPromotion(s);
		/** 2018-06-05 推广佣金 **/
		// cachedThreadPool.execute(new Runnable() {
		//
		// @Override
		// public void run() {
		// sendMailing(s);
		// }
		// });
	}

	// private void sendMailing(SelfRegistering s){
	// StringBuilder sb = new StringBuilder();
	// sb.append("<p><span>").append("dealerId:").append(s.getDealer_id()).append("</span></p>")
	// .append("<p><span>").append("网点名称:").append(s.getCompany_name()).append("</span></p>");
	// sb.append("<p><span>").append("业务范围:")
	// .append((2 ==
	// s.getMerchant_attribute())?"联通售卡":"远特售卡").append("</span></p>");
	// sb.append("<p><span>").append("推广方dealerId:").append(s.getPopchannel()).append("</span></p>");
	// sb.append("<p><span>").append("推广方名称:").append(s.getPopchannel_name()).append("</span></p>");
	// sb.append("<p><span>").append("上级dealerId:").append(s.getSuper_dealer_id()).append("</span></p>");
	// sb.append("<p><span>").append("上级商户名称:").append(s.getSuper_dealer_name()).append("</span></p>");
	// sb.append("<p><span>").append("设备号:").append(s.getKMRecordCode()).append("</span></p>")
	// .append("<p><span>").append("证件号码:").append(s.getIdCard()).append("</span></p>")
	// .append("<p><span>").append("归属城市:").append(s.getCityName()).append("</span></p>")
	// .append("<p><span>").append("具体地址:").append(s.getAddress()).append("</span></p>")
	// .append("<p><span>").append("用户姓名:").append(s.getUser_name()).append("</span></p>")
	// .append("<p><span>").append("用户电话:").append(s.getPhone()).append("</span></p>")
	// .append("<p><span>").append("支付宝账户:").append(s.getAlipay_user_id()).append("</span></p>")
	// .append("<p><span>").append("微信账户:").append(s.getWeixin_user_id()).append("</span></p>")
	// .append("<p><span>").append("门店照片左:").append("</span></p>")
	// .append("<img
	// src='").append(Constant.ums_url).append(s.getImgNo1()).append("'/><br>")
	// .append("<p><span>").append("门店照片右:").append("</span></p>")
	// .append("<img
	// src='").append(Constant.ums_url).append(s.getImgNo2()).append("'/><br>")
	// .append("<p><span>").append("手持照片:").append("</span></p>")
	// .append("<img
	// src='").append(Constant.ums_url).append(s.getImgNo3()).append("'/><br>")
	// .append("<p><span>").append("签名照片:").append("</span></p>")
	// .append("<img
	// src='").append(Constant.ums_url).append(s.getImgNo4()).append("'/><br>");
	// log.info("邮件内容："+sb.toString());
	// String info = "商户激活";
	// List<String> receiveList = new ArrayList<String>();
	// for(String receive:Constant.receiver.split(",")){
	// if(!receive.equals("")){
	// receiveList.add(receive);
	// }
	// }
	// Smtp smtp = new Smtp();
	// try {
	// smtp.sendAttachment("卡盟", info, receiveList,sb.toString());
	// } catch (Exception e) {
	// log.error(e.getMessage(),e);
	// }
	// }

	private void addPromotion(SelfRegistering s) {
		if (s.getSourceType() == Constant.SourceType.XINIU) {
			log.warn("喜牛设备 激活不给推广佣金," + s.getDealer_id());
			return;
		}
		if (s.getIsManage() == 1) {
			log.warn("管理设备激活，不给予推广佣金," + s.getDealer_id());
			return;
		}
		if (ObjectUtils.isNullOrEmpty(s.getSuper_dealer_id())) {
			log.warn("无上级推广方," + s.getDealer_id());
			return;
		}
		DeviceIdInfo deviceInfo = getUserDAO().macGetPromotion(s.getKMRecordCode());
		if (ObjectUtils.isNull(deviceInfo)) {
			log.warn("未找到设备信息，" + s.getKMRecordCode());
			return;
		}
		if (1 != deviceInfo.getIsFanYong()) {
			log.warn("设备不支持推广活动，设备信息：" + deviceInfo.toString());
			return;
		}
		final long time = s.getModifyTime();
		final String date = DateUtils.format(time, "yyyyMMdd");
		ZtgProtionModelDetail ztgProtionModelDetail = userDAO.getIncomeModelDetail(deviceInfo);
		if (ztgProtionModelDetail == null) {
			log.error("设备自推广返佣模式详情未找到，" + deviceInfo.toString());
			return;
		}
		long free = ztgProtionModelDetail.getSupPromotion();
		GavePromotion promotion1 = new GavePromotion();
		promotion1.setTime(time);
		promotion1.setDealerId(s.getSuper_dealer_id());
		promotion1.setDealerName(s.getSuper_dealer_name());
		promotion1.setSrcDealerId(s.getDealer_id());
		promotion1.setSrcDealerName(s.getCompany_name());
		promotion1.setFree(free);
		promotion1.setType(ProType.type7);
		promotion1.setDate(date);
		gavePromotion(promotion1);
		User supUser = getUserDAO().getUserByInviteCode(s.getSuper_dealer_id());
		if (ObjectUtils.nonNull(supUser)) {
			sendMsg(1, time, "", "", s.getPhone(), s.getCompany_name(), supUser.getUserId());
		}
		if (ObjectUtils.isNullOrEmpty(s.getSuperSuperDealerId())) {
			log.warn("无上上级商户");
			return;
		}

		GavePromotion promotion2 = new GavePromotion();
		promotion2.setTime(time);
		promotion2.setDealerId(s.getSuperSuperDealerId());
		promotion2.setDealerName(s.getSuperSuperDealerName());
		promotion2.setSrcDealerId(s.getDealer_id());
		promotion2.setSrcDealerName(s.getCompany_name());
		promotion2.setFree(ztgProtionModelDetail.getSupSupPromotion());
		promotion2.setType(ProType.type25);
		promotion2.setDate(date);
		gavePromotion(promotion2);
		User supSupUser = getUserDAO().getUserByInviteCode(s.getSuperSuperDealerId());
		if (ObjectUtils.nonNull(supSupUser) && ObjectUtils.nonNull(supUser)) {
			sendMsg(2, time, supUser.getPhone(), s.getSuper_dealer_name(), s.getPhone(), s.getCompany_name(),
					supSupUser.getUserId());
		}
	}

	private void gavePromotion(GavePromotion promotion) {
		AsyncUtils.executor().execute(() -> {
			synchronized (this) {
				try {
					String tbname = "tl_merchant_day_" + promotion.getDate().substring(0, 6);
					getUserDAO().createTable(tbname);
					MerchantProInfo oldInfo = getUserDAO().getOldAccount(promotion.getDealerId());
					if (ObjectUtils.isNull(oldInfo)) {
						log.warn("上级商户账户未找到：" + promotion.getDealerId());
						return;
					}
					String oldDate = oldInfo.getUpdateDate();
					long dayHistory = 0;
					long day = 0;
					if (ObjectUtils.isEqual(promotion.getDate().substring(0, 6), oldDate.substring(0, 6))) {
						dayHistory = promotion.getFree();
						if (ObjectUtils.isEqual(promotion.getDate(), oldDate)) {
							day = promotion.getFree();
						}
					}

					MerchantProInfo proInfo = new MerchantProInfo();
					proInfo.setDealerId(promotion.getDealerId());
					proInfo.setDealerName(promotion.getDealerName());
					proInfo.setFree(promotion.getFree());
					proInfo.setMonthFree(0);
					proInfo.setHistoryFree(0);
					proInfo.setCreateTime(promotion.getTime());
					proInfo.setType(promotion.getType());
					proInfo.setDate(promotion.getDate());
					proInfo.setSrcDealerId(promotion.getSrcDealerId());
					proInfo.setSrcDealerName(promotion.getSrcDealerName());

					proInfo.setPromotion(promotion.getFree());
					proInfo.setPromotionDay(day);
					proInfo.setPromotionDayHistory(dayHistory);
					proInfo.setPromotionTotal(promotion.getFree());
					proInfo.setUpdateDate(promotion.getDate());

					boolean add = getUserDAO().gavePromotion(proInfo, tbname);
					log.debug("给予推广佣金操作数据库" + add + "，info:" + proInfo.toString());
				} catch (Exception e) {
					log.error(e.getMessage() + "给予推广佣金报错：" + promotion.toString(), e);
				}
				return;
			}
		});
	}

	/**
	 * 推广消息
	 * 
	 * @param type
	 *            1一级2二级
	 */
	private void sendMsg(int type, final long curTime, final String phoneA, final String userNameA, final String phoneB,
			final String userNameB, final String userId) {
		Message msg = new Message();
		msg.setMsgId(StringUtil.getMsgId(curTime));
		msg.setMsgType(Message.MessageType.POPULARIZE);
		msg.setSender("system");
		msg.setReceiver(userId);
		msg.setCreatTime(curTime);
		msg.setExpTime(curTime + 30 * 24 * 60 * 60 * 1000);
		StringBuilder content = new StringBuilder(256);
		switch (type) {
		case 1:
			content.append("{");
			content.append("\"type\":701");
			content.append(",\"title\": \"商户绑定设备通知\"");
			content.append(",\"annex\":[]");
			content.append(",\"content\":\"尊敬的用户,您推荐的").append(userNameB);
			content.append("(").append(phoneB.substring(0, 3)).append(" **** ").append(phoneB.substring(7, 11))
					.append(")");
			content.append("于" + DateUtils.format(curTime, "yyyy-MM-dd HH:mm:ss") + "成功绑定设备成为您的下级商户");
			content.append("，您将享受相应的佣金奖励，可至自推广激励账户查看激励详情，感谢您的推荐。\"");
			content.append(",\"redirectUrl\":\"\"");
			content.append("}");
			break;
		case 2:
			content.append("{");
			content.append("\"type\":701");
			content.append(",\"title\": \"商户绑定设备通知\"");
			content.append(",\"annex\":[]");
			content.append(",\"content\":\"尊敬的用户,您的下级商户").append(userNameA);
			content.append("(").append(phoneA.substring(0, 3)).append(" **** ").append(phoneA.substring(7, 11))
					.append(")");
			content.append("于" + DateUtils.format(curTime, "yyyy-MM-dd HH:mm:ss") + "成功推荐商户").append(userNameB);
			content.append("(").append(phoneB.substring(0, 3)).append(" **** ").append(phoneB.substring(7, 11))
					.append(")");
			content.append("，成为您的2级自推广商户，您将享受相应的佣金奖励，可至自推广激励账户查看激励详情。\"");
			content.append(",\"redirectUrl\":\"\"");
			content.append("}");
			break;
		default:
			break;
		}
		log.debug("send msg:" + content.toString());
		msg.setContent(content.toString());

		messageDAO.save(msg);
	}

	interface ProType {
		/** 上级推广金 **/
		int type7 = 7;
		/** 上上级推广金 **/
		int type25 = 25;
	}

	@Override
	public String getShqpInfo(JSONObject json) {
		try {
			final String dealerId = json.getString("dealerId");
			if (ObjectUtils.isNullOrEmpty(dealerId)) {
				log.warn("param dealerId error");
				return StatusCode.PARAM_ERROR.json().toString();
			}
			Merchant merchant = merchantDAO.getByDealerId(dealerId);
			StringBuilder sb = new StringBuilder(128);
			/**** 授权牌信息 ****/
			sb.append("{");
			addShqpInfo(dealerId, sb, merchant.getSourceType());
			sb.append("}");
			/**** 授权牌信息 ****/
			return StatusCode.SUCCESS.json().data(sb.toString());
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return StatusCode.SYSTEM_EXCEPTION.json().toString();
		}
	}

	@Override
	public String userClientAndRegion() {
		boolean is = false;
		JSONObject j = new JSONObject();
		/*
		 * List<userClientAndRegion> list = userDAO.getUserClient(); if
		 * (list.size() > 0) { is = userDAO.updateUserClientDetail(list); if
		 * (is) { j.put("更改tb_user_client_detail数量", list.size()); } }
		 */
		List<userClientAndRegion> list = userDAO.getUserRegion();
		j.put("查询tb_merchant有效地址数量", list.size());
		if (list.size() > 0) {
			List<userClientAndRegion> newList = new ArrayList<userClientAndRegion>();
			for (userClientAndRegion info : list) {
				TransAddr.GpsInfo gpsInfo = TransAddr.geocoding(getApiAk(), info.getStoreAddress());
				if (!StringUtil.isNULL(gpsInfo)) {
					is = isIdentical(gpsInfo.getProvince(), info.getStoreAddress());
					if (is) {
						userClientAndRegion newInfo = new userClientAndRegion();
						String userRegion = gpsInfo.getProvince() + gpsInfo.getCity() + gpsInfo.getDistrict();
						newInfo.setUserRegion(userRegion);
						newInfo.setMerchantId(info.getMerchantId());
						newList.add(newInfo);
					}
				}
			}
			is = userDAO.updateUserRegion(newList);
			if (is) {
				j.put("更改合法tb_merchant使用地区数量", newList.size());
			}
		}
		/*
		 * is = userDAO.clearTmsi(); if (is) { j.put("清楚Tmsi", "完成"); }
		 */
		return StatusCode.SUCCESS.toDiyJson("data", j);
	}

	// 判断编译后地址是否在源地址
	private boolean isIdentical(String gpsAddress, String storeAddress) {
		if (gpsAddress.contains("特别行政区")) {
			gpsAddress = gpsAddress.replaceAll("特别行政区", "");
		} else if (gpsAddress.contains("维吾尔自治区")) {
			gpsAddress = gpsAddress.replaceAll("维吾尔自治区", "");
		} else if (gpsAddress.contains("回族自治区")) {
			gpsAddress = gpsAddress.replaceAll("回族自治区", "");
		} else if (gpsAddress.contains("壮族自治区")) {
			gpsAddress = gpsAddress.replaceAll("壮族自治区", "");
		} else if (gpsAddress.contains("自治区")) {
			gpsAddress = gpsAddress.replaceAll("自治区", "");
		} else if (gpsAddress.contains("省")) {
			gpsAddress = gpsAddress.replaceAll("省", "");
		} else if (gpsAddress.contains("市")) {
			gpsAddress = gpsAddress.replaceAll("市", "");
		}
		if (storeAddress.contains(gpsAddress)) {
			return true;
		}
		return false;
	}

	private Random random = new Random();

	protected String getApiAk() {
		final String aks = userDAO.redis_get(RedisConstant.BAIDU_API_AK);
		if (ObjectUtils.isNullOrEmpty(aks)) {
			return Constant.ApiConf.BAIDU_MAP_APK;
		}
		List<String> list = Stream.of(aks.split(",")).collect(Collectors.toList());
		return list.stream().skip(random.nextInt(list.size())).findAny().get();
	}

    @Override
    public String addJobNumAuditBack(JSONObject json) {
        String orderId = json.getString("orderId");
        String result = json.getString("result"); // 审核结果：1通过2拒绝3待分配4已分配
        String desc = json.getString("desc");
        String gztCheckResult = json.getString("gztCheckResult");
        String remarks = json.getString("remarks"); // 审核备注,ECS
        String auditType = json.getString("auditType"); // 审核类型：1自动审核，2人工审核
        String customer = json.getString("customer"); // 审核人ID,ECS
        log.info("执行添加子工号审核结果回调接口：addJobNumAuditBack，审核类型auditType为：" + auditType);
        if (StringUtils.isBlank(orderId)) {
            log.error("param orderId is null");
            return StatusCode.PARAM_ERROR.toJSON("orderId不能为空");
        }
        if (StringUtils.isBlank(result)) {
            log.error("param result is null");
            return StatusCode.PARAM_ERROR.toJSON("result不能为空");
        }
        if (StringUtils.isBlank(auditType)) {
            log.error("param auditType is null");
            return StatusCode.PARAM_ERROR.toJSON("auditType不能为空");
        }
        JobNumberAudit audit = getUserDAO().getJobNumAuditByOrderId(orderId);
        if (Objects.isNull(audit)) {
            log.error("该订单不存在,orderId为" + orderId);
            return StatusCode.SYSTEM_EXCEPTION.toJSON("该订单不存在,请联系管理员");
        }
        audit.setOrderStatus(Integer.parseInt(result)); // 审核结果：1通过2拒绝3待分配4已分配
        audit.setAutoAuditDesc(desc);
        audit.setAutoAuditResult(Integer.parseInt(result)); // 自动审核结果：1：通过，2：拒绝
        audit.setGztCheck(gztCheckResult);
        audit.setRemarks(remarks);
        audit.setUserTypeId(9);
        String invite = null;
        if(1 == audit.getOrderStatus()){
            invite = userDAO.getInviteCode();
            if (StringUtils.isBlank(invite)) {
                log.error("getInviteCode return null," + json.toString());
                return StatusCode.SYSTEM_EXCEPTION.toJSON();
            }
        }

        boolean r = getUserDAO().addUser(audit, invite, Integer.parseInt(auditType), customer);
        if (!r) {
            log.warn("addUser return false," + json);
            return StatusCode.SYSTEM_EXCEPTION.toJSON("系统忙，请稍后再试");
        }
        if (auditType.equals("2")) { // 人工审核
            if (1 == Integer.parseInt(result)) {
                // 发送短信消息
                sendMsg(audit.getSonUserPhone(), Constant.MSG_INGO);
                // 发送欢迎消息
                addWelcomeMsg(audit.getUserId(), 0, 1);
            } else {
                // 发送短信消息
                sendMsg(audit.getSonUserPhone(), String.format("人工审核失败，失败原因%s。", remarks));
            }
            // 发送业务审核结果消息
            sendAddJobNumMsg(audit.getMainUserId(), audit.getRemarks(), Integer.parseInt(result));
        }
        if (auditType.equals("1")) { // 自动审核
            if (2 == Integer.parseInt(result)) {
                // 发送短信消息
                sendMsg(audit.getSonUserPhone(), String.format("自动审核失败，失败原因%s。", desc));
                // 发送业务审核结果消息
                sendAddJobNumMsg(audit.getMainUserId(), audit.getAutoAuditDesc(), Integer.parseInt(result));
            }
        }

        return StatusCode.SUCCESS.toJSON();
    }

    private void sendAddJobNumMsg(String userId, String remarks, int result) {
        Message msg = new Message();
        long curTime = Clock.systemDefaultZone().millis();
        msg.setMsgId(StringUtil.getMsgId(curTime));
        msg.setMsgType(Message.MessageType.BUSINESS);
        msg.setSender("system");
        msg.setCreatTime(curTime);
        msg.setExpTime(curTime + 30 * 24 * 60 * 60 * 1000);
        msg.setReceiver(userId);
        StringBuilder content = new StringBuilder(256);
        switch (result) {
            case 1:
                content.append("{");
                content.append("\"type\":247");
                content.append(",\"title\": \"商户添加子工号结果通知\"");
                content.append(",\"annex\":[]");
                content.append(",\"content\":\"");
                content.append("尊敬的用户,您已于");
                content.append(DateUtils.format(curTime, "yyyy-MM-dd HH:mm:ss"));
                content.append("成功添加子工号！");
                content.append("\"");
                content.append(",\"redirectUrl\":\"\"");
                content.append("}");
                break;
            case 2:
                content.append("{");
                content.append("\"type\":248");
                content.append(",\"title\": \"商户添加子工号结果通知\"");
                content.append(",\"annex\":[]");
                content.append(",\"content\":\"");
                content.append("尊敬的用户,您的添加子工号申请于");
                content.append(DateUtils.format(curTime, "yyyy-MM-dd HH:mm:ss"));
                content.append("被拒绝，原因是：");
                content.append(remarks);
                content.append("。请按照要求，重新提交申请。");
                content.append("\"");
                content.append(",\"redirectUrl\":\"\"");
                content.append("}");
                break;
            default:
                break;
        }
        log.info("send msg:" + content.toString());
        msg.setContent(content.toString());

        messageDAO.save(msg);
    }

}
